﻿#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using System.Security.Cryptography;
/// <summary>
/// 资源工具
/// </summary>
public class SFAssetUtility
{
    /// <summary>
    /// 从文件加载资源
    /// </summary>
    /// <param name="_assetBundleName">资源名称</param>
    /// <param name="_onCallback">回调</param>
    /// <param name="_extraArgs">额外参数</param>
    public static void LoadFromFile(string _assetBundleName, System.Action<Object, object[]> _onCallback, params object[] _extraArgs)
    {
#if UNITY_EDITOR
        Object obj = AssetDatabase.LoadMainAssetAtPath(_assetBundleName);
        _onCallback?.Invoke(obj, _extraArgs);
#else
        _onCallback?.Invoke(null, _extraArgs);
#endif
    }

    public static void WriteFile(string savepath, byte[] data) {
        FileInfo localmainifest = new FileInfo(savepath);
        if (!localmainifest.Directory.Exists)
        {
            Directory.CreateDirectory(localmainifest.Directory.FullName);
        }
        File.WriteAllBytes(savepath, data);
    }

    /// <summary>
    ///  读取文件
    /// </summary>
    /// <param name="assetpath">从Asset开始的路径</param>
    /// <param name="data">byte[]</param>
    /// <returns></returns>
    public static bool LoadFile(string assetpath, out byte[] data)
    {
        data = null;

        string path = Path.Combine(SFGlobalSetting.assetBundleRoot, assetpath).Replace('\\', '/');
        if (File.Exists(path))
        {
            data = File.ReadAllBytes(path);
        }
        else
        {
            path = Path.Combine(SFGlobalSetting.streamingAssetsRoot, assetpath).Replace('\\', '/');
            data = LoadURLAsset(path);

        }
        return data != null;
    }
    /// <summary>
    /// 加载URL 上的文件内容
    /// </summary>
    /// <param name="urlpath">URLPath</param>
    /// <returns>byte[]</returns>
    public static byte[] LoadURLAsset( string urlpath)
    {
        byte[] data = null;
        UnityWebRequest plartform_www = UnityWebRequest.Get(urlpath);
        plartform_www.timeout = 2;
        var async = plartform_www.SendWebRequest();
        while (!async.isDone)
        {

        }
        if (plartform_www.result == UnityWebRequest.Result.ProtocolError)
        {
            Debug.Log("读取不到本地文件 error " + plartform_www.error);
        }
        else
        {
            data = plartform_www.downloadHandler.data;
        }

        return data;
    }

    public static string[] GetAllFileFormDirectory(string dirpath)
    {
        List<string> paths = new List<string>();
        DirectoryInfo directory = new DirectoryInfo(dirpath);
        FileInfo[] files = directory.GetFiles();
        DirectoryInfo[] directories = directory.GetDirectories();
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i].Extension != ".meta")
            {
                paths.Add(files[i].FullName);
            }

        }
        for (int i = 0; i < directories.Length; i++)
        {
            paths.AddRange(GetAllFileFormDirectory(directories[i].FullName));
        }
        return paths.ToArray();
    }

    /// <summary>
    /// 文件校验
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static string GetMD5HashFromFile(string fileName)
    {
        FileStream file = new FileStream(fileName, FileMode.Open);

        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        md5.ComputeHash(file);
        file.Close();
        byte[] b = md5.Hash;
        md5.Clear();
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < b.Length; i++)
        {
            sb.Append(b[i].ToString("X2"));
        }
        return sb.ToString();
    }
}
